"""
错误映射模块
简化错误映射逻辑，提供统一的错误映射机制
"""
from typing import Optional, Dict, Type, Pattern, Match
import re
import logging

from ...core.exceptions import (
	LLMException, ProviderError, AuthenticationError, RateLimitError,
	ConnectionError, TimeoutError, ServerError, QuotaExceededError,
	ContentFilterError, ModelNotFoundError, InvalidRequestError,
	InputTooLongError
)

# 设置日志
logger = logging.getLogger("connllm.errors")

# 常见错误映射模式
COMMON_ERROR_PATTERNS = {
	# 网络和连接错误
	r"timeout|timed out": TimeoutError,
	r"connect|connection|refused|unreachable": ConnectionError,
	
	# 服务器错误
	r"server error|5\d\d|internal server|service unavailable": ServerError,
	
	# 认证错误
	r"auth|unauthorized|invalid key|invalid api key|authentication|apikey": AuthenticationError,
	
	# 速率限制
	r"rate limit|ratelimit|too many requests|429|too frequent": RateLimitError,
	
	# 资源限制
	r"quota|billing|payment|invoice|credit|insufficient_quota": QuotaExceededError,
	
	# 输入问题
	r"context.*too long|maximum context|too long|token limit": InputTooLongError,
	
	# 内容过滤
	r"content policy|content filter|moderation|inappropriate|harmful": ContentFilterError,
	
	# 模型问题
	r"model not found|cannot find model|unknown model": ModelNotFoundError,
}

# 提供商特定错误模式
PROVIDER_ERROR_PATTERNS = {
	"anthropic": {
		r"invalid_api_key": AuthenticationError,
		r"rate_limited": RateLimitError,
		r"invalid_request": InvalidRequestError,
	},
	"openai": {
		r"insufficient_quota|account_deactivated": QuotaExceededError,
		r"context_length_exceeded": InputTooLongError,
	},
	"moonshot": {
		r"authentication.*failed": AuthenticationError,
		r"exceed.*limit": RateLimitError,
	},
	"openrouter": {
		r"credits.*depleted": QuotaExceededError,
	},
}

def map_error_from_provider(provider: str, error: Exception, model: Optional[str] = None) -> ProviderError:
	"""
	将原始错误映射为标准LLM异常
	简化版本的错误映射器，使用模式匹配和正则表达式
	
	Args:
		provider: 提供商类型
		error: 原始错误
		model: 模型名称
		
	Returns:
		标准化的LLM异常
	"""
	# 已经是ProviderError的直接返回
	if isinstance(error, ProviderError):
		return error
	
	# 提取错误信息和类型
	error_message = str(error).lower()
	error_type = error.__class__.__name__
	
	# 记录原始错误
	logger.debug(f"映射{provider}原始错误: {error_type}: {error_message}")
	
	# 1. 尝试匹配提供商特定模式
	if provider in PROVIDER_ERROR_PATTERNS:
		for pattern, error_class in PROVIDER_ERROR_PATTERNS[provider].items():
			if re.search(pattern, error_message):
				return error_class(str(error), provider, model)
	
	# 2. 尝试匹配通用错误模式
	for pattern, error_class in COMMON_ERROR_PATTERNS.items():
		if re.search(pattern, error_message):
			# 特殊处理速率限制错误的重试时间
			if error_class == RateLimitError:
				retry_after = None
				retry_match = re.search(r"retry after (\d+)", error_message)
				if retry_match:
					try:
						retry_after = int(retry_match.group(1))
					except (ValueError, IndexError):
						pass
				
				return RateLimitError(str(error), provider, model, retry_after)
			
			# 特殊处理模型不存在错误
			if error_class == ModelNotFoundError and model:
				return ModelNotFoundError(f"模型'{model}'不存在或不可用", provider, model)
			
			return error_class(str(error), provider, model)
	
	# 3. 通过错误类名映射常见异常
	if "Timeout" in error_type:
		return TimeoutError(str(error), provider, model)
	elif "Connection" in error_type:
		return ConnectionError(str(error), provider, model)
	elif "NotFound" in error_type and model:
		return ModelNotFoundError(f"模型'{model}'不存在或不可用", provider, model)
	
	# 4. 默认为通用提供商错误
	return ProviderError(str(error), provider, model)
